/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.sigmatrix.h5.dao.SyncTaskDao;
import com.sigmatrix.h5.dao.impl.common.impl.BaseDaoImpl;
import com.sigmatrix.h5.entity.SyncTask;
import com.sigmatrix.h5.enums.TableEnum;
import com.sigmatrix.h5.exception.DaoException;

/**
 * @ClassName: SyncTaskDaoImpl
 * @Description: 异步任务数据库操作接口实现
 * @author youjun 
 * @date 2017-11-27 16:04:46
 */
@Repository(value = "syncTaskDao")
public class SyncTaskDaoImpl extends BaseDaoImpl<SyncTask> implements SyncTaskDao {

	/** 注入jdbcTemplate */
	@Autowired
	private transient JdbcTemplate jdbcTemplate;

	@Override
	public SyncTask findById(final Integer id, final String enterpriseCode) throws DaoException {
		final StringBuilder sql = new StringBuilder("SELECT * FROM ").append(getTname(enterpriseCode, TableEnum.SYNCTASK)).append(" WHERE _id = ?");
		final Object[] params = new Object[] { id };
		final List<SyncTask> list = jdbcTemplate.query(sql.toString(), params, new SyncTaskRowMapper());
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public int save(final SyncTask syncTask, final String enterpriseCode) throws DaoException {

		final StringBuilder sql = new StringBuilder(
				"INSERT INTO ").append(getTname(enterpriseCode, TableEnum.SYNCTASK)).append("(_request_params, _response_result, _status, _is_success, _response_code, _sync_error_msg, _type, _type_sign, _create_time, _update_time, _remark, _response_msg) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		final Object[] params = new Object[] { syncTask.getRequestParams(), syncTask.getResponseResult(),
				syncTask.getStatus(), syncTask.getIsSuccess(), syncTask.getResponseCode(), syncTask.getSyncErrorMsg(),
				syncTask.getType(), syncTask.getTypeSign(), syncTask.getCreateTime(), syncTask.getUpdateTime(),
				syncTask.getRemark(), syncTask.getResponseMsg() };
		/*final int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, Types.SMALLINT, Types.VARCHAR,
				Types.VARCHAR, Types.SMALLINT, Types.VARCHAR, Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR, Types.VARCHAR };
		return jdbcTemplate.update(sql.toString(), params, argTypes);*/
		final KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(final Connection con) throws SQLException {
				final PreparedStatement pstmt = con.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
				int index = 1;
				for (final Object value : params) {
					pstmt.setObject(index, value);
					index++;
				}
				return pstmt;
			}
		}, keyHolder);
		return keyHolder.getKey().intValue();
	}

	@Override
	public int update(final SyncTask syncTask, final String enterpriseCode) throws DaoException {

		final StringBuilder sql = new StringBuilder(
				"UPDATE ").append(getTname(enterpriseCode, TableEnum.SYNCTASK)).append(" SET _request_params = ?, _response_result = ?, _status = ?, _is_success = ?, _response_code = ?, _sync_error_msg = ?, _type = ?, _type_sign = ?, _create_time = ?, _update_time = ?, _remark = ?, _response_msg = ? WHERE _id = ?");
		final Object[] params = new Object[] { syncTask.getRequestParams(), syncTask.getResponseResult(),
				syncTask.getStatus(), syncTask.getIsSuccess(), syncTask.getResponseCode(), syncTask.getSyncErrorMsg(),
				syncTask.getType(), syncTask.getTypeSign(), syncTask.getCreateTime(), syncTask.getUpdateTime(),
				syncTask.getRemark(), syncTask.getResponseMsg(), syncTask.getId() };
		final int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, Types.SMALLINT, Types.VARCHAR,
				Types.VARCHAR, Types.SMALLINT, Types.VARCHAR, Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR,
				Types.VARCHAR, Types.INTEGER };
		return jdbcTemplate.update(sql.toString(), params, argTypes);
	}

	/**(non-Javadoc)
	 *@Title: updateStatus
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.dao.SyncTaskDao#updateStatus(java.lang.String, int, short)
	 *@author youjun
	 *@date 2017年11月27日 下午8:12:58
	 */
	@Override
	public int updateStatus(String enterpriseCode, int syncTaskId, short status)
			 throws DaoException {

		final StringBuilder sql = new StringBuilder(
				"UPDATE ").append(getTname(enterpriseCode, TableEnum.SYNCTASK)).append(" SET _status = ? WHERE _id = ?");
		Object[] params = new Object[] {status, syncTaskId};
		int[] argTypes = new int[] {Types.SMALLINT, Types.INTEGER};
		return jdbcTemplate.update(sql.toString(), params, argTypes);
	}
	
	/**
	 * @ClassName: SyncTaskRowMapper
	 * @Description: 封装返回的实体
	 * @author youjun 
	 * @date 2017-11-27 16:04:46
	 */
	public class SyncTaskRowMapper implements RowMapper<SyncTask> {

		/**
		 * (non-Javadoc)
		 * 
		 * @Title: mapRow
		 * @Description: 
		 * @see
		 * @author youjun @date 2017-11-27 16:04:46
		 */
		@Override
		public SyncTask mapRow(final ResultSet resultSet, final int rowNum) throws SQLException {
			final SyncTask syncTask = new SyncTask();
			syncTask.setId(resultSet.getInt("_id"));
			syncTask.setRequestParams(resultSet.getString("_request_params"));
			syncTask.setResponseResult(resultSet.getString("_response_result"));
			syncTask.setStatus(resultSet.getShort("_status"));
			syncTask.setIsSuccess(resultSet.getShort("_is_success"));
			syncTask.setResponseCode(resultSet.getString("_response_code"));
			syncTask.setResponseMsg(resultSet.getString("_response_msg"));
			syncTask.setSyncErrorMsg(resultSet.getString("_sync_error_msg"));
			syncTask.setType(resultSet.getShort("_type"));
			syncTask.setTypeSign(resultSet.getString("_type_sign"));
			syncTask.setCreateTime(resultSet.getTimestamp("_create_time"));
			syncTask.setUpdateTime(resultSet.getTimestamp("_update_time"));
			syncTask.setRemark(resultSet.getString("_remark"));
			return syncTask;
		}
	}

}
